using System;
using VisualWip.Core.Interfaces;

namespace VisualWip.Core
{
    public class NamedObjectBase<T> : IPersistable, IEquatable<T>, IComparable<T>, IComparable
        where T : NamedObjectBase<T>
    {
        public string Name { get; protected set; }
        public int SortOrder { get; protected set; }

        #region IComparable Members

        public int CompareTo(object obj)
        {
            var other = obj as T;
            return other == null ? 1 : CompareTo(other);
        }

        #endregion

        #region IComparable<T> Members

        public int CompareTo(T other)
        {
            return SortOrder - other.SortOrder;
        }

        #endregion

        #region IEquatable<T> Members

        public bool Equals(T other)
        {
            return Name.Equals(other.Name);
        }

        #endregion

        #region IPersistable Members

        public PersistenceTree Persist(string name)
        {
            var settings = new PersistenceTree(name, this);
            settings.Add(() => Name);
            settings.Add(() => SortOrder);
            return settings;
        }

        public void Load(PersistenceTree settings)
        {
            Name = settings.Get(() => Name,String.Empty);
            SortOrder = settings.Get(() => SortOrder,0);
        }

        #endregion

        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
    }
}